package cn.dengyongsheng;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.ByteString;

import cn.dengyongsheng.Config.*;

/**
 * Hello world!
 *
 */
public class ProtoBufTestApp {
    /* 字符串类型的IP地址转为int32 */
    public static int ip_to_int32(String ip) {
        String[] ip_arr = ip.split("\\.");
        int ip_int = 0;
        for (int i = 0; i < 4; i++) {
            ip_int = ip_int << 8;
            ip_int = ip_int | Integer.parseInt(ip_arr[i]);
        }
        return ip_int;
    }

    public static int bytes_to_int(byte[] bytes) {
        return (bytes[0] & 0xFF) << 24 |
                (bytes[1] & 0xFF) << 16 |
                (bytes[2] & 0xFF) << 8 |
                (bytes[3] & 0xFF);
    }

    public static void main(String[] args) {
        /* 初始化 */
        /* 将上述信息放到同一个结构体config中 */
        PB_TerninalConfigration configration = PB_TerninalConfigration.newBuilder()
                /* 构造网络配置信息 */
                .setNetInfo(PB_NetInfo.newBuilder()
                        .setUseDhcp(true)
                        .setDns(bytes_to_int(new byte[] { (byte) 192, (byte) 168, 1, 1 }))
                        .setIp(bytes_to_int(new byte[] { (byte) 192, (byte) 168, 1, 2 }))
                        .setSubnetMask(bytes_to_int(new byte[] { (byte) 255, (byte) 255, (byte) 255, 0 }))
                        .setGateway(bytes_to_int(new byte[] { (byte) 192, (byte) 168, 1, 2 }))
                        .setMacAddr(ByteString.copyFrom(new byte[] { (byte) 0xff, 0x01, 0x02, 0x03, 0x04, 0x05 }))
                        .build())
                /* 构造设备信息 */
                .setDeviceInfo(PB_DeviceInfo.newBuilder()
                        .setTerminalSn("202300001")
                        .setLogLevel(1)
                        .build())
                /* 构造服务端配置 */
                .setServerInfo(PB_ServerInfo.newBuilder()
                        .setHostname("dengyongsheng.cn")
                        .setPort(8080)
                        .build())
                .build();

        System.out.println("原始信息：");
        System.out.println(configration.toString());

        /* 将结构体转换为字节流 */
        System.out.println("序列化结果：");
        byte[] configration_bytes = configration.toByteArray();
        /* 打印字节 */
        for (byte b : configration_bytes) {
            System.out.print(String.format("%02x ", b));
        }
        System.out.println();

        /* 反序列化 */
        try {
            PB_TerninalConfigration configration_deserialized = PB_TerninalConfigration.parseFrom(configration_bytes);
            System.out.println("反序列化结果：");
            System.out.println(configration_deserialized.toString());
        } catch (InvalidProtocolBufferException e) {
            System.err.println("反序列化错误" + e.toString());
        }
    }
}
